<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>栈结构的实现</title>
</head>
<body>
    <script>
        //Method(方法):一般与对象实例有联系的成为方法
        //function(函数):与方法相反
        //栈结构基于数组的实现
        class Stack{
            //模拟栈
            items = [];

            //1.push压栈
            push(element){
                return this.items.push(element);
            }

            //2.pop弹栈
            pop(){
                return this.items.pop();
            }

            //3.peek返回栈顶元素
            peek(){
                return this.items[this.items.length-1]
            }

            //4.isEmpty栈是否为空
            isEmpty(){
                return this.items.length>0 ? false : true;
            }

            //5.size查看栈的长度
            size(){
                return this.items.length;
            }

            //6.toString打印栈的内容
            toString(){
                let str= '';
                this.items.forEach(val => str += val+'  ');
                return str;
            }

        }
        /*
        let s = new Stack();
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        console.log(s.toString()); */

        //例子:将十进制转成二进制,dec:十进制的缩写,bin:二进制的缩写,2:to
        function dec2bin(decNum) {
            //创建栈实例  
            let s = new Stack();
            //循环压入十进制数模2的值,十进制转二进制的算法:除2取余
            while(decNum>0){
                s.push(decNum % 2)
                //更新十进制数
                decNum = Math.floor(decNum / 2)
            }
            let bin = '';
            //循环拼接弹栈的值
            while(!s.isEmpty()){
                bin += s.pop();
            }
            //返回二进制值
            return bin;
        }
        console.log(dec2bin(3));
    </script>

</body>
</html>